import * as uuid from "uuid";
import Types from "../typings";

class Common<T> {
  Model: T & Types.Common.PlainObjType;

  constructor(Model: T & Types.Common.PlainObjType) {
    this.Model = Model;
  }

  // 生成一个 uuid
  static CreateUuid: () => string = () => uuid.v4();

  // 获取当前登录的用户id
  getLoginUserId: (req: Types.Express.ConvertRequest) => string = (req) => {
    const {
      loginUser: { id: creatorId },
    } = <Types.Express.ConvertRequest>req;

    return creatorId;
  };

  Count: (query: Types.Common.PlainObjType) => any = (query = {}) => {
    return this.Model.countDocuments(query);
  };

  Find: (query: Types.Common.PlainObjType) => any = (query = {}) => {
    return this.Model.find(query);
  };

  SaveOne: (data: Types.Common.PlainObjType) => any = (data = {}) => {
    const id = Common.CreateUuid();
    return new (this.Model as any)({ id, ...data }).save();
  };

  UpdateOne: (
    query: Types.Common.PlainObjType,
    updateContent: Types.Common.PlainObjType
  ) => any = (query = {}, updateContent = {}) => {
    return this.Model.findOneAndUpdate(query, updateContent, {
      new: true,
      runValidators: true /* 触发验证*/,
    });
  };

  RemoveOne: (query: Types.Common.PlainObjType) => any = (query = {}) => {
    return this.Model.findOneAndDelete(query);
  };

  DeleteMany: (query: Types.Common.PlainObjType) => any = (query: {}) => {
    return this.Model.deleteMany(query);
  };

  updateMany: (
    query: Types.Common.PlainObjType,
    updateContent: Types.Common.PlainObjType
  ) => any = (query = {}, updateContent = {}) => {
    return this.Model.updateMany(query, updateContent);
  };
}

export default Common;
